package com.ews.onlineexchange.controller;

import java.util.ArrayList;
import java.util.List;

import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.DataEntity;
import com.ews.onlineexchange.model.ServiceBuyer;
import com.ews.onlineexchange.service.EntityQuery;

@Model
public class UnauditBulletinList extends EntityQuery<Bulletin> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public UnauditBulletinList() {
		setMaxResults(MAX_RESULTS_NORMAL);
		setOrder("createDate DESC");
	}

	@Override
	protected List<Predicate> getRestrictions(CriteriaBuilder cb, Root<Bulletin> entity) {
		List<Predicate> restrictions = new ArrayList<Predicate>();
		restrictions.add(cb.equal(entity.get("delFlag"), DataEntity.DEL_FLAG_NORMAL));
		Join<Bulletin, ServiceBuyer> buyer = entity.join("buyer");
		//根据县区过滤
		super.addBulletinRegionRestriction(restrictions,buyer,cb);
//		restrictions.add(cb.isNull(entity.get("auditResult") ));
		Predicate equal = cb.equal(entity.get("auditResult"), new Boolean(true));
		Predicate notOver = cb.isFalse(entity.<Boolean>get("over"));
		restrictions.add(cb.or(cb.isNull(entity.get("auditResult")), cb.and(equal, notOver)));
		String projectName = (String)getParameterValues().get("projectName");
		if (!StringUtils.isBlank(projectName))
			restrictions.add(cb.like(entity.get("projectName"), getStringRestriction(projectName)));
		return restrictions;
	}

	@Inject
	EntityManager entityManager;
	private String QUERY_UNAUDIT_BULLETIN_EQL = "SELECT bulletin FROM Bulletin bulletin "+
			" WHERE auditResult IS NULL AND delFlag = '0'  ORDER BY createDate DESC";
	private int MAX_SIZE = 7;		
	public List<ServiceBuyer> getUnauditUnaduitBestBulletins(){
		return entityManager.createQuery(QUERY_UNAUDIT_BULLETIN_EQL).setMaxResults(MAX_SIZE).getResultList();
	}
	

}
